import axios from 'axios';
import { reportForms } from "@/api/index";
import { mapState, mapActions } from "vuex";
import { columnsScreen, derives, tableDataOlds, tableDataNews } from "./columns";
import { getYearsArr, getCurrentDate, getMonthArr, getFullYear } from "./rmsRequest";
import SortingSelector from "./SortingSelector.vue";
import RmsDetail from "@components/table/dialog/RmsDetail"
export default {
  name: "rmsDetails",
  data () {
    return {
      combineTr: 7,
      dialogVisible: false,
      dialogShow: false,
      particularYear: getFullYear(),
      particularMonth: '',
      time: '',
      pickDate: '',
      currentYear: '',
      currentMonth: '',
      currentTime: '',
      pickerOptions: {
        onPick: this.getPickDate,
        disabledDate: this.disabledDate
      },
      derive: {},
      shipData: {},
      tableData: [],
      workOptions: '',
      options: {
        yearOptions: getYearsArr(2, 2),
        monthOptions: getMonthArr(), // 只能选择当月-2之前的月份
        supplierOptions: [],
        workOptions: [
          {
            value: 2,
            label: "经销商直发"
          },
          {
            value: 3,
            label: "干线直发"
          },
          {
            value: 1,
            label: "OEM直发"
          },
          {
            value: 4,
            label: "经销商直发+干线直发"
          }
        ],
        CDCwarehouse: [
          {
            value: "无锡CDC",
            label: "无锡CDC仓库"
          },
          {
            value: "华北CDC",
            label: "华北CDC仓库"
          }
        ],
        OEMOptions: []
      },
      monthList: [],
      columns: [],
      params: {
        supplierCompanyId: "",
        topType: '',
        queryStartTime: "",
        queryEndTime: "",
        topWarehouseShortName: "",
        oemGysCode: ""
      },
      supplierCompanyName: '',
      isTopSupplier: '11',
      companyName: '22',
      form: {},
      dataForm: {},
      orderTypesName: "",
      orderTypesName01: "",
      titleYear: "",
      titleMonth: "",
      supplierName: "",
      shortName: "",
      dialogText: "",
      kpiTitle: "",
      // 考核时间
      kpiStatisticsDate: null,
      topGysName: "",
      tableDataOld: tableDataOlds(),
      tableDataNew: tableDataNews(),
      resultObj: {},
      warehouseDatum: {},
      haveData01: false,
      haveData02: false,
      loading: false,
      spanArr: [], // 二维数组，用于存放单元格合并规则
      first: 0, // 用于存储相同项的开始index
      showTitle: false,
      userInfo: sessionStorage.getItem('userInfo')
    };
  },
  computed: {
    ...mapState({
      // tenantId: (state) => state.login.tenantId,
      menuId: (state) => state.menu.menu.menuId
    }),
    user () {
      return JSON.parse(this.userInfo)
    },
    tenantId () {
      return this.user?.tenantId
    }
  },
  mounted () {
    this.columns = columnsScreen(this.menuId);
    this.derive = derives(this.menuId);
    setTimeout(() => {
      this.locationInHone();
    }, 1500);
  },
  methods: {
    // 是否带参
    locationInHone () {
      let now = new Date();
      this.tableData = JSON.parse(JSON.stringify(this.tableDataOld));
      this.currentYear = now.getFullYear()
      this.currentMonth = now.getMonth() + 1;
      this.currentTime = String(now.getFullYear()) + (this.currentMonth < 10 ? '0' + String(this.currentMonth) : String(this.currentMonth));
      // this.search(2);
      this.carrierSearch()
      this.sheetShow();
    },
    async carrierSearch () {
      let { data } = await reportForms.carrierSearchs({}, '1')
      let datas = data.data
      let code = data.code
      if (code === 0) {
        this.options.supplierOptions = datas;
      } else {
        this.options.supplierOptions = []
      }
    },
    async carrierChange (e) {
      this.params.oemGysCode = ''
      this.options.OEMOptions = []
      this.options.supplierOptions.forEach(item => {
        if (item.supplierCompanyId == e) {
          this.supplierName = item.name
        }
      })
      let { data } = await reportForms.carrierSearchs({ supplierCompanyId: e }, '2')
      let datas = data.data
      let code = data.code
      if (code === 0) {
        this.options.OEMOptions = datas;
      } else {
        this.options.OEMOptions = []
      }
    },
    topType () {
      this.params.topWarehouseShortName = ''
      this.params.oemGysCode = ''
    },
    // 查询
    async search (type) {
      // this.params.page = type == 1?1:this.pageNo,
      // this.params.size = this.pageSize
      if (!this.particularMonth) {
        this.$message.warning("请选择考核月份");
        return
      }
      if (!this.params.supplierCompanyId) {
        this.$message.warning("请选择承运方");
        return
      }
      if (!this.params.topType) {
        this.$message.warning("请选择业务类型");
        return
      }
      this.loading = true
      let { data } = await reportForms.rmsList(this.params, this.menuId)
      let datas = data.data
      let code = data.code
      if (code === 0) {
        // this.tableData = []
        // this.tableData = data.records
        this.titleYear = this.particularYear;
        this.titleMonth = this.particularMonth;
        this.orderTypesName01 = this.selectName(
          this.options.workOptions,
          this.params.topType
        );
        this.titleYear = this.particularYear;
        this.titleMonth = this.particularMonth;
        this.topGysName = this.params.oemGysName;
        this.shortName = this.params.topWarehouseShortName;
        if (this.params.topWarehouseShortName) this.haveData01 = true;
        if (this.params.oemGysName) this.haveData02 = true;
        this.showTitle = true;
        // this.$store.commit('isOperation', true)
        this.resultObj = datas ? datas : {};
        // this.resultObj.detailVoList = JSON.stringify(data.records.detailVoList);
        // todo wangcan
        this.kpiStatisticsDate = getCurrentDate(2);
        this.loading = false
        if (this.params.topType == 4) {
          this.resultDataBoth(this.resultObj);
        } else {
          this.resultData(this.resultObj);
        }
      }  else if (code == 403) {
        this.loading = false;
        this.dialogShow = true
        this.kpiTitle = '考核提示'
        this.dialogText = data.message?data.message:''
      } else {
        this.showTitle = false
        this.loading = false
      }
    },
    clearYear (e) {
      if (this.particularMonth) {
        this.params.queryStartTime = this.particularYear + this.particularMonth
        this.params.queryEndTime = this.particularYear + this.particularMonth
      } else {
        this.params.queryStartTime = this.particularYear + '01'
        this.params.queryEndTime = this.particularYear + this.particularMonth
      }

    },
    clearMonth (e) {
      this.params.queryStartTime = this.$moment(this.time[0]).format("YYYYMM");
      this.params.queryEndTime = this.$moment(this.time[1]).format("YYYYMM");
    },
    // 导出
    async handleExport () {
      if (JSON.stringify(this.resultObj) == '{}') {
        this.$message.warning("没有可要导出的数据！");
        return false;
      }
      const link = document.createElement('a');
      let params = this.params
      axios.post(`${this.$processEnvUrl}/report/top/topExport`,
        params,
        { //请求头需要的一些配置
          headers: {
            "Authorization": 'Bearer ' + sessionStorage.getItem("token")
          },
          responseType: 'blob',//设置返回类型
        }
      ).then((res) => {
        // let blob =  res.data
        if (res) {
          const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
          let _fileName = 'kpi考核' + (this.kpiStatisticsDate ? this.kpiStatisticsDate : '')
          link.style.display = 'none';
          // 兼容不同浏览器的URL对象
          const url = window.URL || window.webkitURL || window.moxURL;
          link.href = url.createObjectURL(blob);
          link.download = _fileName;
          link.click();
          window.URL.revokeObjectURL(url);
        } else {
          this.$message.warning("下载的文件出错");
          return
        }
      })
    },
    // 查询导出未读数
    ...mapActions({
      searchCount: "login/exportCount"
    }),
    // 清除
    resetForm () {
      this.time = []
      this.params = {
        supplierCompanyId: "",
        topType: '',
        queryStartTime: "",
        queryEndTime: "",
        topWarehouseShortName: "",
        oemGysCode: ""
      }
      this.showTitle = false
      this.tableData = JSON.parse(JSON.stringify(this.tableDataOld));
      if (this.params.topType == 4) {
        this.tableData = JSON.parse(JSON.stringify(this.tableDataNew));
      } else {
        this.tableData = JSON.parse(JSON.stringify(this.tableDataOld));
      }
      this.supplierName = '';
      this.particularYear = getFullYear();
      this.particularMonth = '';
      this.titleYear = '';
      this.titleMonth = '';
      this.orderTypesName01 = '';
      this.shortName = '';
      this.topGysName = '';
      this.kpiStatisticsDate = '';
      delete this.params.queryStartTime;
      delete this.params.queryEndTime;
    },
    refreshOpen () {
      if (!this.particularMonth) {
        this.loading = false
        this.$message.warning("月份不能为空，请选择月份后重试！");
        return
      }
      this.refresh()
    },
    async refresh () {
      this.loading = true
      let form = {
        queryStartTime: this.params.queryStartTime,
        queryEndTime: this.params.queryEndTime
      }
      let { data } = await reportForms.rmsList(form, 36101)
      let datas = data.data
      let code = data.code
      if (code == 0) {
        this.$message.warning("数据正在刷新，预计在5分钟后进行更新！");
        setTimeout(() => {
          this.loading = false;
        }, 1500)
      } else if (code == 403) {
        this.loading = false;
        this.dialogShow = true
        this.kpiTitle = '重算考核数据提示'
        this.dialogText = data.message?data.message:''
      }else {
        this.loading = false;
      }
    },
    detail () {
      const { href } = this.$router.resolve({
        name: 'kpiDetails',
        query: {
          uuId: this.resultObj.uuId
        }
      });
      window.open(href, "_blank");
    },
    dialog (data) {
      this.dialogVisible = true;
      this.shipData = data;
    },
    handleClose () {
      this.dialogVisible = false;
    },
    handleShow () {
      this.dialogShow = false;
    },
    //限制筛选时效一年
    getPickDate (pick) {
      this.pickDate = pick;
    },
    disabledDate (date) {
      const { minDate, maxDate } = this.pickDate;
      if (minDate && !maxDate) {
        const diff = Math.abs(minDate.valueOf() - date.valueOf());
        if (diff > 1000 * 3600 * 24 * 365) {
          return true;
        }
      }
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      // 合并表格
      let num = 3;
      if (columnIndex === 0) {
        if (rowIndex % num === 0) {
          return {
            rowspan: num,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    toFixeTwoPercent (num) {
      // 小数转百分比，保留两位小数
      num = typeof num === 'undefined' ? 0 : num
      num = num * 100 + ''
      if (num.indexOf('.') === -1) {
        num = num + '.00%'
      } else if (num.split('.')[1].length === 1) {
        num = num + '0%'
      } else {
        num = (num * 1).toFixed(2) + '%'
      }
      return num
    },
    sheetShow () {
      this.rowSpan(0, "work");
      this.rowSpan(1, "subOption");
      this.rowSpan(2, "description");
      this.rowSpan(4, "calculation");
      this.rowSpan(5, "proportion");
      this.rowSpan(8, "score");
    },
    resultData (data) {
      if (this.params.topType == 2) {
        this.tableData[1].standard = data.ldShReachStand;
        this.tableData[2].standard = data.ldHdReachStand;
        this.tableData[1].actual = data.zeroArrivalTimeRate
          ? `${data.zeroArrivalTimeRate}%`
          : "0%";
        this.tableData[2].actual = data.zeroReceiptTimeRate
          ? `${data.zeroReceiptTimeRate}%`
          : "0%";
      } else if (this.params.topType == 3) {
        this.tableData[1].standard = data.gxShReachStand;
        this.tableData[2].standard = data.gxHdReachStand;
        this.tableData[1].actual = data.drylineArrivalTimeRate
          ? `${data.drylineArrivalTimeRate}%`
          : "0%";
        this.tableData[2].actual = data.drylineReceiptTimeRate
          ? `${data.drylineReceiptTimeRate}%`
          : "0%";
      } else {
        this.tableData[1].standard = data.oemShReachStand;
        this.tableData[2].standard = data.oemHdReachStand;
        this.tableData[1].actual = data.oemArrivalTimeRate
          ? `${data.oemArrivalTimeRate}%`
          : "0%";
        this.tableData[2].actual = data.oemReceiptTimeRate
          ? `${data.oemReceiptTimeRate}%`
          : "0%";
      }
      this.tableData[0].actual = data.deliveryTimeRate
        ? `${data.deliveryTimeRate}%`
        : "0%";
      this.tableData[3].actual = data.hwLoseNumber;
      this.tableData[4].actual = data.hdLoseNumber;
      this.tableData[5].actual = data.losePercentageRate?data.losePercentageRate+'%':'0%';
      this.tableData[0].score = data.deliveryTimeScore ? data.deliveryTimeScore : 0;
      this.tableData[1].score = data.multipleShServiceScore
        ? data.multipleShServiceScore
        : 0;
      this.tableData[2].score = data.multipleHdServiceScore
        ? data.multipleHdServiceScore
        : 0;
      this.tableData[3].score = data.hwLoseScore;
      this.tableData[4].score = data.hdLoseScore;
      this.tableData[5].score = data.losePercentageScore;
    },
    resultDataBoth (data) {
      this.tableData[2].standard = data.gxShReachStand;
      this.tableData[1].standard = data.ldShReachStand;
      this.tableData[4].standard = data.gxHdReachStand;
      this.tableData[3].standard = data.ldHdReachStand;
      this.tableData[0].actual = data.deliveryTimeRate
        ? `${data.deliveryTimeRate}%`
        : "0%";
      this.tableData[2].actual = data.drylineArrivalTimeRate
        ? `${data.drylineArrivalTimeRate}%`
        : "0%";
      this.tableData[1].actual = data.zeroArrivalTimeRate
        ? `${data.zeroArrivalTimeRate}%`
        : "0%";
      this.tableData[4].actual = data.drylineReceiptTimeRate
        ? `${data.drylineReceiptTimeRate}%`
        : "0%";
      this.tableData[3].actual = data.zeroReceiptTimeRate
        ? `${data.zeroReceiptTimeRate}%`
        : "0%";
      this.tableData[5].actual = data.hwLoseNumber;
      this.tableData[6].actual = data.hdLoseNumber;
      this.tableData[7].actual = data.losePercentageRate?data.losePercentageRate+'%':'0%';
      this.tableData[0].score = data.deliveryTimeScore ? data.deliveryTimeScore : 0;
      this.tableData[1].score = data.multipleShServiceScore
        ? data.multipleShServiceScore
        : 0;
      this.tableData[3].score = data.multipleHdServiceScore
        ? data.multipleHdServiceScore
        : 0;
      this.tableData[5].score = data.hwLoseScore;
      this.tableData[6].score = data.hdLoseScore;
      this.tableData[7].score = data.losePercentageScore;
    },
    timeFilter (year, month) {
      if (!year || !month) return;
      return `${year}${month < 10 ? `0${month}` : month}`;
    },
    rowSpan (idx, prop) {
      this.spanArr[idx] = [];
      this.first = 0;
      this.tableData.forEach((item, index) => {
        if (idx == 8) {
          if (this.params.topType == 4) {
            if (
              this.tableData[index]["description"] == "干线直发" &&
              this.tableData[index - 1]["description"] == "经销商直发"
            ) {
              this.spanArr[idx][this.first] += 1;
              this.spanArr[idx].push(0);
            } else {
              this.spanArr[idx].push(1);
              this.first = index;
            }
          } else {
            this.spanArr[idx].push(1);
            this.first = index;
          }
        } else {
          if (index === 0) {
            this.spanArr[idx].push(1);
            this.first = 0;
          } else {
            if (this.params.topType == 4 || !this.params.topType) {
              if (
                this.tableData[index][prop] ===
                this.tableData[index - 1][prop] &&
                this.tableData[index][prop]
              ) {
                this.spanArr[idx][this.first] += 1; // 有相同项
                this.spanArr[idx].push(0); // 名称相同后往数组里面加一项0
              } else {
                this.spanArr[idx].push(1); // 同列的前后两行单元格不相同
                this.first = index;
              }
            } else {
              if (
                this.tableData[index][prop] ===
                this.tableData[index - 1][prop] &&
                this.tableData[index][prop]
              ) {
                if (
                  this.tableData[index][prop] == "经销商直发" ||
                  this.tableData[index][prop] == "干线直发" ||
                  this.tableData[index][prop] == "OEM直发"
                ) {
                  this.spanArr[idx].push(1);
                  this.first = index;
                } else {
                  this.spanArr[idx][this.first] += 1; // 有相同项
                  this.spanArr[idx].push(0); // 名称相同后往数组里面加一项0
                }
              } else {
                this.spanArr[idx].push(1); // 同列的前后两行单元格不相同
                this.first = index;
              }
            }
          }
        }
      });
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (this.params.topType === 4) {
        if (columnIndex > 1 && rowIndex > 16) return [1, 6];
      } else {
        if (columnIndex > 1 && rowIndex > 14) return [1, 6];
      }
      if (
        columnIndex == 0 || columnIndex == 1 || columnIndex == 2 ||
        columnIndex == 4 || columnIndex == 5 || columnIndex == 8
      ) {
        for (let i = 0; i < 10; i++) {
          if (columnIndex === i) {
            const _row = this.spanArr[i][rowIndex];
            const _col = _row > 0 ? 1 : 0;
            return {
              rowspan: _row,
              colspan: _col
            };
          }
        }
      }
    },
    selectName (arr, val) {
      if (!val || !arr || arr.length == 0) return
      return arr.find(item => item.value === val).label
    },
    gridChange () {
      if (this.params.topType == 4) {
        this.tableData = JSON.parse(JSON.stringify(this.tableDataNew));
        this.sheetShow();
      } else {
        this.tableData = JSON.parse(JSON.stringify(this.tableDataOld));
        this.sheetShow();
        this.tableData[1].description = this.orderTypeName;
        this.tableData[2].description = this.orderTypeName;
      }
    }
  },
  watch: {
    params: {
      deep: true,
      handler (val) {
        this.params.queryStartTime =
          this.particularMonth && this.particularYear
            ? `${this.particularYear}${this.particularMonth < 10 ? '0' + this.particularMonth : this.particularMonth}`
            : "";
        this.params.queryEndTime = this.timeFilter(
          this.particularYear,
          this.particularMonth
        );
        // this.form.supplierCompanyName =  this.$tools.selectName(this.options.supplierOptions,this.form.supplierCompanyId)
        this.orderTypeName = this.selectName(
          this.options.workOptions,
          this.params.topType
        );
        // this.form.oemGysName = this.$tools.selectName(this.options.OEMOptions,this.form.oemGysCode)
        this.gridChange();
      }
    },
    particularYear: {
      immediate: true,
      handler (val, old) {
        if (val) {
          if (old) {
            this.particularMonth = "";
          }
          let currentYear = new Date().getFullYear();
          if (val == currentYear) {
            this.options.monthOptions = getMonthArr(val, true);
          } else {
            this.options.monthOptions = getMonthArr(val, false);
          }
        }
      }
    },
    particularMonth: {
      immediate: true,
      handler (val, old) {
        if (val) {
          this.params.queryStartTime =
            this.particularMonth && this.particularYear
              ? `${this.particularYear}${this.particularMonth < 10 ? '0' + this.particularMonth : this.particularMonth}`
              : "";
          this.params.queryEndTime = this.timeFilter(
            this.particularYear,
            this.particularMonth
          );
        }
      }
    }
  },
  components: {
    RmsDetail,
    SortingSelector
  }
};